<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="项目代码" prop="projectCode">
        <el-input
                v-model="queryParams.projectCode"
                placeholder="请输入项目代码"
                clearable
                size="small"
                @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="题库名称" prop="questionBankName">
        <el-input
                v-model="queryParams.questionBankName"
                placeholder="请输入题库名称"
                clearable
                size="small"
                @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="试题类型" prop="questionType">
        <el-select v-model="queryParams.questionType" placeholder="试题类型" clearable size="small">
          <el-option
                  v-for="dict in questionTypeOptions"
                  :key="dict.code"
                  :label="dict.name"
                  :value="dict.code"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="有无图片" prop="isImage">
        <el-select v-model="queryParams.isImage" placeholder="试题类型" clearable size="small">
          <el-option
                  v-for="dict in isImageOptions"
                  :key="dict.code"
                  :label="dict.name"
                  :value="dict.code"
          />
        </el-select>
      </el-form-item>-->
      <el-form-item label="试题类型" prop="isMustExam">
        <el-select v-model="queryParams.isMustExam" placeholder="试题类型" clearable size="small">
          <el-option
                  v-for="dict in isMustExamOptions"
                  :key="dict.code"
                  :label="dict.name"
                  :value="dict.code"
          />
        </el-select>
      </el-form-item>

      <el-form-item style="margin-left: 10px">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button style="margin-left: 10px" icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini"
                   @click="handleAddArmy"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple"
                   @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" icon="el-icon-upload2" size="mini"
                   @click="handleImport"
                   v-hasPermi="['exam:question:query']"
        >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-download" size="mini"
                   @click="handleExport"
                   v-hasPermi="['exam:question:query']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="questionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="试题编号" align="center" prop="questionNumber" :show-overflow-tooltip="true"/>
      <el-table-column label="题库类型" align="center" prop="questionBankName" :show-overflow-tooltip="true"
                       :formatter="questionBankTypeFormat"/>
      <el-table-column label="试题类型" align="center" prop="questionType" :formatter="questionTypeFormat"/>
      <el-table-column label="选项总数" align="center" prop="optionCount"/>
<!--      <el-table-column label="是否有图片" align="center" prop="isImage" :formatter="isImageFormat"/>-->
      <el-table-column label="是否必考" align="center" prop="isMustExam" :formatter="isMustExamFormat"/>
      <el-table-column label="操作" align="center" class-name="small-padding" width="200">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit"
                     @click="handleEdit(scope.row)"
          >编辑
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-edit"
                     @click="handleReview(scope.row)"
          >预览
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
            v-show="total>0"
            :total="total"
            :page.sync="pageParams.page"
            :limit.sync="pageParams.rows"
            @pagination="getList"
    />

    <!-- 新增或修改试题信息 -->
    <el-dialog :title="title" :visible.sync="open" v-if="open" width="800px" append-to-body>
      <questionForm ref="questionForm" @submitForm="getList" @cancelDialog="cancel"></questionForm>
    </el-dialog>

    <!-- 试题导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
              ref="upload"
              :limit="1"
              accept=".xlsx, .xls"
              :headers="upload.headers"
              :action="upload.url + '?updateSupport=' + upload.updateSupport"
              :disabled="upload.isUploading"
              :on-progress="handleFileUploadProgress"
              :on-success="handleFileSuccess"
              :auto-upload="false"
              drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport"/>
          是否更新已经存在的试题数据
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 预览区域 -->
    <el-dialog :title="'试题预览'" :visible.sync="openReview" v-if="openReview" width="600px" append-to-body>
      <el-row>
        <el-col :span="24" class="text">
          <span v-html="reviewData.questionStems"></span>
        </el-col>
        <div v-if="reviewData.questionOptionList.length">
          <el-col :span="24" v-for="option in reviewData.questionOptionList" class="text">
            {{ option.optionTag + '.' }}{{ option.optionContent }}
          </el-col>
          <el-col :span="24">
            <p>正确答案：{{ reviewData.standardAnswer }}</p>
          </el-col>
        </div>
        <el-col :span="24" v-if="reviewData.questionType == '2'">
          <p>正确答案：{{ reviewData.standardAnswer }}</p>
        </el-col>
        <el-col :span="24">
          <p>参考解析</p>
        </el-col>
        <el-col :span="24" class="text">
          <span v-html="reviewData.questionParse"></span>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeReview">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {getToken} from "@/utils/auth";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import {
    importTemplate,
    exportQuestion,
    delQuestion,
    listQuestion,
    getQuestionByQuestionId
  } from "@/api/question/question";
  import questionForm from "./form/questionForm"
  import elUeditor from "./util/ueditor";


  export default {
    name: "questionBank",
    components: {
      questionForm,
      elUeditor
    },
    data() {
      return {
        //选中试题编号数组
        questionNumbers: [],
        //选中试题id数组
        questionIds: [],
        // 按钮loading
        buttonLoading: false,
        // 遮罩层
        loading: false,
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 试题表格数据
        questionList: [],
        //预览数据
        reviewData: {},
        // 弹出层标题
        title: "",
        // 是否弹出层
        open: false,
        // 试题预览开关
        openReview: false,
        // 试题类型数据字典
        questionTypeOptions: [],
        //是否有图片数据字典
        isImageOptions: [],
        //是否必考数据字典
        isMustExamOptions: [],
        // 日期范围
        dateRange: [],
        // 试题导入参数
        upload: {
          // 是否显示弹出层（证书导入）
          open: false,
          // 弹出层标题（证书导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的证书数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: {Authorization: "Bearer " + getToken()},
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/exam/question/importData"
        },
        // 分页参数
        pageParams: {
          page: 1,
          rows: 10,
        },
        // 查询参数
        queryParams: {
          projectCode: undefined,
          projectName: undefined,
          questionBankName: undefined,
          questionType: undefined,
        },
      };
    },
    created() {
      this.getList();
      //查询试题类别字典状态
      this.getDicts("question_type").then(response => {
        this.questionTypeOptions = response.responseBody.result;
      });
      //试题是否有图片
      this.getDicts("question_is_image").then(response => {
        this.isImageOptions = response.responseBody.result;
      })
      //试题是否必考
      this.getDicts("question_is_must_exam").then(response => {
        this.isMustExamOptions = response.responseBody.result;
      })
    },
    methods: {
      /** 查询试题列表 */
      getList() {
        this.loading = true;
        listQuestion({
          'pageParameter': this.pageParams,
          'searchParams': this.addDateRange(this.queryParams, this.dateRange)
        }).then(response => {
          this.questionList = response.responseBody.result;
          this.total = response.responseBody.pageParameter.totalCount;
          this.loading = false;
        });
      },
      // 试题类型字典翻译
      questionTypeFormat(row, column) {
        return this.selectDictLabel(this.questionTypeOptions, row.questionType);
      },
      // 题库类型转换
      questionBankTypeFormat(row, col) {
        return row.projectCode + row.questionBankName;
      },
      //是否有图片转换
      isImageFormat(row) {
        return this.selectDictLabel(this.isImageOptions, row.isImage);
      },
      //是否必考转换
      isMustExamFormat(row) {
        return this.selectDictLabel(this.isMustExamOptions, row.isMustExam);
      },
      // 取消按钮
      cancel() {
        this.open = false;
      },

      /** 搜索按钮操作 */
      handleQuery() {
        this.pageParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },

      /** 新增试题按钮操作 */
      handleAddArmy() {
        this.open = true;
        this.title = "新增试题";
        //新增默认选项为单选题
        this.$nextTick(() => {
          this.$refs.questionForm.init();
        })
      },

      /** 试题编辑按钮操作 */
      handleEdit(row) {
        const id = row.questionId;
        this.open = true;
        this.title = "修改试题";
        this.$nextTick(() => {
          this.$refs.questionForm.init(id);
        })
      },

      /** 删除按钮操作 */
      handleDelete(row) {
        const questionNumbers = row.questionNumber || this.questionNumbers
        const questionIds = row.questionId || this.questionIds
        this.$confirm('确认删除试题编号为：（' + questionNumbers + '）的数据项？','提示',{
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: "warning"
        }).then(() => {
          this.loading = true;
          delQuestion(questionIds).then(response => {
            this.msgSuccess("删除成功");
            this.getList();
          })
        }).catch(() => {
        }).finally(() => {
          this.loading = false;
        });
      },
      //预览
      handleReview(row) {
        getQuestionByQuestionId(row.questionId).then(resqonse => {
          this.reviewData = resqonse.responseBody;
          // 如果试题存在选项，则去除选项中多余的<p>标签
          if(this.reviewData.questionOptionList.length > 0){
            // 去除选项中多余的<p>标签
            this.reviewData.questionOptionList.forEach(item => {
              item.optionContent = item.optionContent.replace('<p>','').replace('</p>','')
            })
          }
          this.openReview = true;
          if (this.reviewData.questionType == '2') {
            this.reviewData.standardAnswer = this.reviewData.standardAnswer == '0' ? '正确' : '错误';
          }
        })
      },
      //关闭预览
      closeReview() {
        this.openReview = false;
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.questionNumbers = selection.map(item => item.questionNumber)
        this.questionIds = selection.map(item => item.questionId)
        this.multiple = !selection.length
      },

      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('确认导出所有试题数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return exportQuestion(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
      },
      /** 导入按钮操作 */
      handleImport() {
        this.upload.title = "试题导入";
        this.upload.open = true;
      },
      /** 下载模板操作 */
      importTemplate() {
        importTemplate().then(response => {
          this.download(response.msg);
        });
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert(response.msg, "导入结果", {dangerouslyUseHTMLString: true});
        this.getList();
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },

    }
  }
  ;
</script>

<style scoped>
    .title {
        font-size: 24px;
        font-weight: bold;
        padding: 10px;
    }

    .text {
        padding: 10px;
    }
</style>
